<template>
  <a-spin :spinning="confirmLoading">
    <!-- 主表单区域 -->
    <a-form :form="form">
      <a-row>
        <a-col :span="24">
          <a-form-item label="仓库" :labelCol="{ span: 2 }" :wrapperCol="{ span: 10 }">
            <j-popup
              :disabled="formDisabled"
              v-decorator="['storeName', validatorRules.storeName]"
              :list-data.sync="listData"
              :trigger-change="true"
              org-fields="id,store_name"
              dest-fields="storeId,storeName"
              code="store_info"
              @callback="popupCallback"
            />
          </a-form-item>
          <a-form-item label="goodsId" style="height: 0px; overflow: hidden; margin-bottom: 0">
            <a-input :disabled="formDisabled" v-decorator="['storeId']"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-show="isShowRemark == '审核'">
        <a-col :span="24">
          <a-form-item label="审核意见" :labelCol="{ span: 2 }" :wrapperCol="{ span: 10 }">
            <a-textarea v-model="remark" placeholder="请填写审核意见" auto-size />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="补货单明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="replenishGoodsBillDetailTable.loading"
          :columns="replenishGoodsBillDetailTable.columns"
          :dataSource="replenishGoodsBillDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          @valueChange="handleSelectRowChange"
          :actionButton="true"
        >
          <template v-slot:spSlot="props">
            <span :style="{ color: !props.text ? 'red' : '#000000a6' }">{{ !props.text ? '无货' : props.text }}</span>
          </template>
          <template v-slot:specsValues="props">
            <!--<div class="box" @click="boxClick(props)">
              {{props.text}}
            </div>-->
            <!--详情的时候查看这个-->
            <a-select
              style="width: 100%"
              @change="xialaxuanze(props, $event)"
              :value="props.text"
              @focus="boxClick(props)"
              :disabled="formDisabled"
              v-if="formDisabled"
            >
              <a-select-option :key="i.id" v-for="(i, index) in optionsArray">
                {{ i.specsValues }}
              </a-select-option>
            </a-select>
            <!--编辑的时候查看这个-->
            <a-select
              style="width: 100%"
              @change="xialaxuanze(props, $event)"
              :defaultValue="props.text"
              @focus="boxClick(props)"
              :disabled="formDisabled"
              v-else
            >
              <a-select-option :key="i.id" v-for="(i, index) in optionsArray">
                <!--                <a-tag color="#108ee9" v-for="(m,index1) in i.specsValues">{{m.attributeName+':'+m.attributeValues}}</a-tag>-->
                {{ i.specsValues }}
              </a-select-option>
            </a-select>
          </template>
        </j-editable-table>
      </a-tab-pane>
    </a-tabs>
    <!--<a-modal
      title="商品规格选择"
      :visible="visible1"
      @ok="handleOk1"
      @cancel="handleCancel1"
    >
      <a-select  style="width: 100%" @change="xialaxuanze">
        <a-select-option :value="i.id" v-for="(i,index) in optionsArray">
          <a-tag color="#108ee9" v-for="(m,index1) in i.specsValues">{{m.attributeName+':'+m.attributeValues}}</a-tag>
        </a-select-option>
      </a-select>
    </a-modal>-->
  </a-spin>
</template>

<script>
import pick from 'lodash.pick'
import { getAction } from '@/api/manage'
import { putReplenishGoodsBill } from '@/api/order'
import { FormTypes, VALIDATE_NO_PASSED, getRefPromise, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
// import func from '../../../../vue-temp/vue-editor-bridge'

export default {
  name: 'ReplenishGoodsBillForm',
  mixins: [JEditableTableMixin],
  components: {
    JFormContainer,
  },
  watch: {
    listData: {
      immediate: true,
      handler(val) {
        if (val) {
          let row = {
            storeId: val[0].id,
            storeName: val[0].store_name,
          }
          this.popupCallback(row)
        }
      },
    },
    isShowRemark: {
      immediate: true,
      handler(val) {
        if (val == '审核') {
          this.listType = 'list2'
        } else {
          this.listType = 'list1'
        }
      },
    },
  },
  data() {
    return {
      index: 0,
      appId: '',
      remark: '',
      listData: null,
      listType: 'list1',
      optionsArray: [],
      visible1: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 },
      },

      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0,
      validatorRules: {
        storeName: {
          rules: [{ required: true, message: '请选择仓库!' }],
        },
      },
      refKeys: ['replenishGoodsBillDetail'],
      tableKeys: ['replenishGoodsBillDetail'],
      activeKey: 'replenishGoodsBillDetail',
      // 补货单明细
      replenishGoodsBillDetailTable: {
        loading: false,
        dataSource: [],

        columns: [
          /*{
              title: '补货单主表编号',
              key: 'replenishId',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },*/

          {
            title: '补货团长',
            key: 'customerName',
            type: FormTypes.popup,
            popupCode: 'shopInfo',
            destFields: 'customerId,customerName', //回填到表单的列名，多个以逗号隔开
            orgFields: 'id,shop_name', //online报表查询出来的列名，多个以逗号隔开
            // field:"wx_no",//online报表查询出来的列名，多个以逗号隔开wx_no
            width: '200px',
            placeholder: '请选择${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '请选择${title}!' }],
          },
          {
            title: '商品',
            key: 'goodsName',
            type: FormTypes.popup,
            popupCode: 'group_order_goods_select',
            destFields: 'goodsId,goodsName,unitName',
            orgFields: 'id,name,unit_name',
            // field:"id",
            width: '200px',
            placeholder: '请选择${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '请选择${title}!' }],
          },
          {
            title: '补货商品规格id',
            key: 'goodsSpecsId',
            type: 'hidden',
          },
          {
            title: '商品ID',
            key: 'goodsId',
            type: 'hidden',
          },
          {
            title: '团长ID',
            key: 'customerId',
            type: 'hidden',
          },
          {
            title: '补货商品规格',
            key: 'specsValues',
            type: FormTypes.slot,
            slotName: 'specsValues',
            width: '300px',
            placeholder: '请选择${title}',
            defaultValue: '',
            validateRules: [
              {
                handler(type, value, row, column, callback, target) {
                  let { values } = target.getValuesSync({ validate: false })
                  let count = 0
                  for (let resultElement of values) {
                    if (resultElement['goodsSpecsId'] == '') {
                      if (++count >= 1) {
                        callback(false, '请选择${title}!')
                        return
                      }
                    }
                  }
                  callback()
                },
                message: '请选择${title}!',
              },
            ],
          },
          /*{
              title: '临时的',
              key: 'linshi',
              type: FormTypes.input,
              width:"100px",
              placeholder: '请选择${title}',
              defaultValue: '',
            },*/
          {
            title: '单位',
            key: 'unitName',
            type: FormTypes.input,
            disabled: true,
            width: '100px',
          },
          {
            title: '数量',
            key: 'number',
            type: FormTypes.inputNumber,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: 1,
            validateRules: [{ required: true, message: '请输入${title}!' }],
          },
          {
            title: '仓位',
            key: 'spaceId_dictText',
            type: 'hidden',
            width: '100px',
          },
        ],
      },
      url: {
        add: '/order/replenishGoodsBill/add',
        edit: '/order/replenishGoodsBill/edit',
        queryById: '/order/replenishGoodsBill/queryById',
        replenishGoodsBillDetail: {
          list1: '/order/replenishGoodsBill/listReplenishGoodsBillDetailByMainId',
          list2: '/order/replenishGoodsBill/listReplenishGoodsBillDetailSpaceByMainId',
        },
        getGoodsName: '/goods/listGoods?name=', //查询商品ID列表
        queryByGoodsId: 'goodsspecs/bizGoodsSpecs/queryByGoodsId/',
        getGoodsSpecsStr: '/goodsspecs/bizGoodsSpecs/getGoodsSpecsStr/',
      },
    }
  },
  props: {
    isShowRemark: {
      type: String,
      default: '',
      required: false,
    },
    //流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false,
    },
    //表单模式：false流程表单 true普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false,
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  methods: {
    handleOk1() {
      /** 触发表单验证 */
      this.getAllTable()
        .then((tables) => {
          /** 一次性验证主表和所有的次表 */

          return validateFormAndTables(this.form, tables)
        })
        .then((allValues) => {
          let arr = allValues.tablesValue[0].values
          for (let i = 0; i < arr.length; i++) {
            const element = arr[i]
            if (!element.unitName) {
              this.$message.warning('请选择已设置单位的商品')
              return false
            }
          }
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          return this.request(formData)
        })
        .catch((e) => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
    },
    addBefore() {
      this.form.resetFields()
      this.replenishGoodsBillDetailTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      let fieldval = pick(this.model, 'storeId', 'storeName')
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.model.id) {
        this.appId = this.model.id

        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.replenishGoodsBillDetail[this.listType],
          params,
          this.replenishGoodsBillDetailTable,
          this.childTableInit
        )
      }
      // 改变子表内容-仓位
      this.setTableSpaceCol()
    },
    childTableInit(res) {
      const {
        message,
        success,
        result: { records },
      } = res
      if (success) {
        for (let i = 0; i < records.length; i++) {
          const item = records[i]
          if (!item.spaceId) {
            this.$emit('update:isShow', false)
            break
          }
        }
      }
    },
    setTableSpaceCol() {
      let c = this.replenishGoodsBillDetailTable.columns
      if (['审核', '详情'].includes(this.isShowRemark)) {
        if (this.isShowRemark == '详情' && ![0, 2].includes(this.model.state)) {
          this.$set(c[c.length - 1], 'type', FormTypes.slot)
          this.$set(c[c.length - 1], 'slotName', 'spSlot')
        }
        if (this.isShowRemark == '审核') {
          this.$set(c[c.length - 1], 'type', FormTypes.slot)
          this.$set(c[c.length - 1], 'slotName', 'spSlot')
        }
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        replenishGoodsBillDetailList: allValues.tablesValue[0].values,
      }
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, 'storeId', 'storeName'))
      /*下面这个是===上面报表选择后清空子表数据，请根据实际情况使用*/
      // this.$refs.replenishGoodsBillDetail.initialize()
    },
    handleSelectRowChange(type, row, column, value, target) {
      // console.log(type, row, column, value, target)
    },
    boxClick(props) {
      this.optionsArray = []
      this.index = props.rowId
      const value = props.getValue()
      getAction(this.url.getGoodsSpecsStr + value.goodsId).then((res) => {
        this.optionsArray = res.result
      })
    },
    handleApp(state) {
      this.confirmLoading = true
      putReplenishGoodsBill({ state, id: this.appId, remark: this.remark })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    //规格下拉选择改变事件
    xialaxuanze(props, e) {
      let { rowId, target } = props
      target.setValues([
        {
          rowKey: rowId,
          values: {
            // 在这里 values 中的 name 是你 columns 中配置的 key
            goodsSpecsId: e,
            // 'specsValues':e,
            // 'linshi':e
          },
        },
      ])
    },
  },
}
</script>

<style scoped>
.box {
  border: 1px solid #d9d9d9;
  color: rgba(0, 0, 0, 0.65);
  height: 32px;
  padding: 4px 11px;
  border-radius: 4px;
  line-height: 1.5;
  background: #fff;
  transition: all 0.3s;
}
.box:hover {
  border-color: #40a9ff;
}
</style>